import React, { Component } from "react";
import { connect } from "react-redux";
import QRCode from "qrcode.react";
import JsBarcode from "jsbarcode";
import { Toast, Modal } from "antd-mobile";
import MainLayout from "../../../component/mainLayout/mainLayout";
import PwdKeyboard from "./pwdKeyboard";
import "./index.scss";
import yhTools from "../../../tools/yh";
import { InterfaceG } from "../../../config/Config";
import SendMSGCode from "../../../component/sendMSGCode/sendMSGCode";
import { getPayDatas } from "../../../Redux/Action/nativeDatas/nativeDatas";
import { debounce } from "lodash";
const alert = Modal.alert;
@connect(state => ({
	getAppPlatformsDatas: state.getAppPlatformsDatas
}))
class PayCode extends Component {
	constructor(props) {
		super(props);
		this.state = {
			backFlag: false,
			isShowPwd: false,
			showMsgBox: false,
			showFullCode: false,
			barCodeVal: "",
			payMoney: "",
			phone: "",
			adListInfo: []
		};
		this.warningAlert = undefined; // 截图警告弹框
		this.cancelOrder = debounce(this.cancelOrder, 1000, {
			leading: true
		});
	}
	componentDidMount() {
		// console.log(this.props.getAppPlatformsDatas);
		this.barCodeOp = {
			displayValue: false,
			width: 3,
			height: 110,
			margin: 0
		};
		// this.ifTrustDevice();
		this.startGetPayCode();
		// 获取进入页面类型
		const state = this.props.location.state || {};
		const { type } = state;
		// 首页进来
		if (type === "index") {
			this.setState({
				backFlag: true
			});
		}
		// 设置截屏监听
		if (window.YHAuthorize) {
			window.YHAuthorize.View.addEventListener(
				"RefreshPayCode",
				this.appRefreshPayCode,
				false
			);
		}
		this.from = this.props.location.query && this.props.location.query.from;
	}
	//模拟扫码枪
	paytrade = code => {
		let data = {
			bar_code: code,
			out_trade_no: Math.random(),
			total_amount: 2000,
			store_id: "CQ0003",
			device_type: "POS_ZY",
			fee_type: "CNY",
			goods_detail:
				"690803,小白兔,5,2|691005,娃哈哈,5.5,2|6913025,农夫山泉满150,16,10",
			list_no: "9459666620181016174846",
			operator_id: "WZF-9300",
			store_name: "永辉测试门店-青禾",
			subject: "振峰测试11-方锦非员工账号",
			terminal_id: "6789",
			trade_type: "BAR_CODE"
		};
		fetch(
			"http://yhjr-sit.yhjr-xhpay-service.sitgw.yonghui.cn/JRPayService/pay/trade",
			{
				body: JSON.stringify(data),
				headers: {
					"content-type": "application/json"
				},
				method: "POST"
			}
		)
			.then(response => response.json())
			.then(res => console.log(res)); // parses response to JSON
	};
	componentWillUnmount() {
		if (window.YHAuthorize) {
			window.YHAuthorize.View.removeEventListener(
				"RefreshPayCode",
				this.appRefreshPayCode,
				false
			);
		}
		this.clearInterval();
	}

	clearInterval() {
		if (this.barInterval) {
			clearInterval(this.barInterval);
			this.barInterval = null;
		}
		if (this.resultInterval) {
			clearInterval(this.resultInterval);
			this.resultInterval = null;
		}
	}
	/**截图处理 */
	appRefreshPayCode = () => {
		this.waitAppRefreshPayCode();
	};
	waitAppRefreshPayCode() {
		if (this.warningAlert) {
			this.warningAlert.close();
			this.warningAlert = undefined;
		}
		this.warningAlert = alert(
			"风险提示",
			"付款码数字仅用于付钱时向商家出示，为防诈骗，请不要发送给他人",
			[
				{
					text: "知道了",
					onPress: () => {
						this.warningAlert = undefined;
					}
				}
			]
		);
		this.getBarCode();
	}
	/**开始获取付款码 */
	startGetPayCode() {
		this.getBarCode();
		this.barInterval = setInterval(this.getBarCode.bind(this), 62 * 1000);
		this.resultInterval = setInterval(
			this.getXcxPayResult.bind(this),
			1 * 1000
		);
	}
	/** 获取支付码 */
	getBarCode() {
		let objs = {
			url: InterfaceG.mmoney_pay_barCode_getBarCode,
			params: {},
			_alertShow: false
		};
		Toast.loading("加载中...", 8);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				this.setState({
					barCodeVal: res.data.barCode
				});
				// 调用 JsBarcode方法生成条形码
				JsBarcode(this.barcode, res.data.barCode, this.barCodeOp);
				// this.paytrade(res.data.barCode);
			} else {
				Toast.info(res.message);
			}
		});
	}
	/**获取支付结果 */
	getXcxPayResult() {
		let objs = {
			url: InterfaceG.mmoney_pay_barCode_getXcxPayResult,
			params: {
				lnid: this.props.getAppPlatformsDatas.lnid
			},
			_alertShow: false
		};
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				const { data } = res;
				const { result, amount } = data;
				if (data.adListInfo && data.adListInfo.length > 0) {
					this.setState({
						//存储轮巡结果中的banner信息
						adListInfo: data.adListInfo
					});
				}
				// result 1：成功  2:失败
				if (result === "1") {
					this.doPayResult(data);
				} else if (result === "2") {
					this.doPayResult(data);
				} else if (result === "0" && !this.state.isShowPwd) {
					//密码框弹起，继续轮训，但不继续处理result=0谈起密码框的情况
					// 交易密码
					this.tradeNo = data.tradeNo;
					this.outTradeNo = data.outTradeNo;
					this.setState({
						isShowPwd: true,
						payMoney: amount
					});
				}
			} else {
				Toast.info(res.message);
			}
		});
	}

	/**交易密码提交 */
	onConfirm(val) {
		if (!val || val.length < 6) {
			Toast.info("请输入正确的密码");
			return;
		}
		if (this.resultInterval) {
			clearInterval(this.resultInterval);
		}
		let objs = {
			url: InterfaceG.offline_confirm,
			params: {
				tradeNo: this.tradeNo,
				password: val,
				outTradeNo: this.outTradeNo
			},
			_alertShow: false
		};
		Toast.loading("加载中...", 8);
		yhTools.request(objs).then(res => {
			Toast.hide();
			if (res.code === "0") {
				let { data } = res;
				data.adListInfo = this.state.adListInfo; //注入存贮的轮巡结果中的banner
				this.doPayResult(data);
			} else if (res.code === "21006") {
				// 交易密码
				alert("系统提示", "支付密码已被锁定，请2小时后再试", [
					{ text: "取消", onPress: () => console.log("取消") },
					{ text: "确定", onPress: () => console.log("确定") }
				]);
			} else {
				Toast.info(res.message);
			}
		});
	}
	/**处理支付成功、失败结果 */
	doPayResult = payData => {
		//清除轮询定时器
		this.clearInterval();
		const {
			result,
			cashBackAmount,
			goodsAmount,
			couponAmount,
			randomAmount,
			amount,
			storeName,
			adListInfo,
			failureReason = "",
			payDiscountAmount,
			payment_time,
			trade_no,
			out_trade_no
		} = payData;
		if (result == "1") {
			// 金额和商户名称存入redux
			this.props._getPayDatas({
				cashBackAmount, //红包金额
				goodsAmount, //商品金额
				couponAmount, //优惠券金额
				randomAmount, //随机立减金额
				amount, //实付金额
				storeName, //商户名称
				payDiscountAmount, //支付活动
				adListInfo, //banner
				payment_time,
				trade_no,
				out_trade_no
			});
			this.props.history.push("/paySuccess");
		} else if (result == "2") {
			this.props._getPayDatas({
				failureReason, //支付失败原因
				adListInfo //banner
			});
			this.props.history.push("/payFail");
		}
	};
	/**校验是否信任设备 */
	ifTrustDevice() {
		let objs = {
			url: InterfaceG.ifTrustDevice,
			params: {
				deviceId: this.props.getAppPlatformsDatas.devicesInfo.deviceId,
				longitude: this.props.getAppPlatformsDatas.longitude,
				latitude: this.props.getAppPlatformsDatas.latitude
			},
			_alertShow: false
		};
		let _that = this;
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				const pageNo = res.data.pageNo;
				if (pageNo == "SMS") {
					//弹框
					_that.deviceTrustToSms();
				} else {
					this.startGetPayCode();
				}
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	/**发送验证码 */
	sendYzm() {
		this.deviceTrustToSms();
	}
	/**校验信任设备发短信 */
	deviceTrustToSms() {
		let objs = {
			url: InterfaceG.deviceTrustToSms,
			params: {},
			_alertShow: false
		};
		let _that = this;
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				_that.sendCode.countdown();
				_that.setState({
					showMsgBox: true,
					phone: res.data.sendSuccessPhone,
					messageSerialNumber: res.data.messageSerialNumber
				});
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	/**验证码提交回调 */
	submitCode(code) {
		this.deviceTrustCheck(code);
	}
	/**校验信任设备验证码校验接口 */
	deviceTrustCheck(code) {
		let objs = {
			url: InterfaceG.deviceTrustCheck,
			params: {
				verifyCode: code,
				deviceId: this.props.getAppPlatformsDatas.devicesInfo.deviceId
			},
			_alertShow: false
		};
		let _that = this;
		yhTools.request(objs).then(res => {
			if (res.code === "0") {
				_that.setState({
					showMsgBox: false
				});
				_that.startGetPayCode();
			} else {
				Toast.info(res.message, 2);
			}
		});
	}
	/**关闭校验弹窗 */
	closeSendModal() {
		console.log("2222222222222");
		this.setState({
			showMsgBox: false
		});
	}
	/**显示全屏条形码 */
	showFullCodeClick(type) {
		const { barCodeVal } = this.state;
		this.setState(
			{
				showFullCode: type
			},
			() => {
				if (type) {
					// 调用 JsBarcode方法生成条形码
					JsBarcode(this.fullBarcode, barCodeVal, {
						displayValue: false,
						width: 3,
						height: 80,
						margin: 0
					});
				} else {
					JsBarcode(this.barcode, barCodeVal, this.barCodeOp);
				}
			}
		);
	}
	//取消支付接口
	cancelOrder = async () => {
		let objs = {
			url: InterfaceG.mmoney_offline_cancel,
			params: {
				outTradeNo: this.outTradeNo,
				payScene: "TPAY"
			}
		};
		try {
			let { code, message } = await yhTools.request(objs);
			if (code === "0") {
				this.closeModal();
			} else {
				Toast.info(message, 2);
				setTimeout(() => {
					this.closeModal();
				}, 2000);
			}
		} catch (error) {
			this.closeModal();
		}
	};
	closeModal = () => {
		this.setState(
			{
				isShowPwd: false
			}
			// this.goBack
		);
		this.startGetPayCode(); //关闭密码弹窗，开启轮询
		document.activeElement.blur();
		this.getBarCode();
	};
	//回到首页
	goBack = () => {
		if (
			this.props.location.state &&
			this.props.location.state.type == "index"
		) {
			return yhTools.closePage();
		}
		if (this.from) {
			this.props.history.push(this.from);
		} else {
			this.props.history.goBack();
		}
	};
	//返回是否取消订单
	goBackAction = () => {
		const { isShowPwd } = this.state;
		if (isShowPwd) {
			this.cancelOrder();
		} else {
			this.goBack();
		}
	};
	render() {
		let _pageParams = {
			header: {
				title: "小辉付",
				goBackAction: this.goBackAction
			},
			sensorsData: {
				title: "付款码"
			},
			history: this.props.history,
			cacheLifecycles: this.props.cacheLifecycles
		};
		const { barCodeVal, isShowPwd, payMoney, showFullCode } = this.state;
		const barCode = yhTools.handelInfo(barCodeVal, 4, 4);
		return (
			<MainLayout pageParams={_pageParams}>
				{/* 放大条形码 */}
				{showFullCode ? (
					<div
						className="fullbar-box"
						onClick={this.showFullCodeClick.bind(this, false)}
					>
						<div className="barcodeval">{barCodeVal}</div>
						<img
							className="barcode"
							ref={ref => {
								this.fullBarcode = ref;
							}}
							alt=""
						/>
					</div>
				) : (
					<div className="com-pay_code-box">
						<div className="banner"></div>
						<div className="content-box">
							<div className="logo"></div>
							<div className="content-tip">向商家展示以完成付款</div>
							<svg
								onClick={this.showFullCodeClick.bind(this, true)}
								className="barcode"
								ref={ref => {
									this.barcode = ref;
								}}
							/>
							<div className="barcodeval">{barCode}</div>
							{barCodeVal ? <QRCode className="code" value={barCodeVal} /> : ""}
							<p className="pay-text">每分钟自动刷新</p>
						</div>

						<div className="code-tip">
							安全提醒：请勿向外人泄露付款码页面任何信息！
						</div>
					</div>
				)}
				<PwdKeyboard
					closeModal={this.cancelOrder}
					payMoney={payMoney}
					onConfirm={this.onConfirm.bind(this)}
					isShow={isShowPwd}
				></PwdKeyboard>
				<SendMSGCode
					sendSuccessPhone={this.state.phone}
					ref={ref => {
						this.sendCode = ref;
					}}
					getYZMCode={this.sendYzm.bind(this)}
					submitCode={this.submitCode.bind(this)}
					closeSendModal={this.closeSendModal.bind(this)}
					showMsgBox={this.state.showMsgBox}
				/>
			</MainLayout>
		);
	}
}
function mapStateToProps(state) {
	return state;
}

function mapDispatchToProps(dispatch) {
	return {
		_getPayDatas: options => {
			dispatch(getPayDatas(options));
		}
	};
}

const PayCodePage = connect(mapStateToProps, mapDispatchToProps)(PayCode);
export default PayCodePage;
